package com.bytz.modules.cms.c4c.model;

import com.bytz.common.exception.BytzBootException;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.ApiModelProperty;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang3.StringUtils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Getter
@Setter
public class C4cResponse<T> {

    @JsonProperty("d")
    private C4cResponseData<T> data;

    @Getter
    @Setter
    public static class C4cResponseData<T> {
        @ApiModelProperty("下一页url")
        @JsonProperty("__next")
        private String next;

        @ApiModelProperty("c4c返回的信息列表")
        @JsonProperty("results")
        private T results;

        /**
         * 获取下一页url中的param:skipToken
         */
        public String getSkipToken() {
            if (StringUtils.isBlank(next)) {
                return null;
            } else {
                // 取出url中的参数$skiptoken
                String url = next + "&";
                Pattern r = Pattern.compile("(\\?|&){1}\\$skiptoken=.*?&{1}");
                Matcher matcher = r.matcher(url);
                if (matcher.find()) {
                    return matcher.group(0).split("=")[1].replace("&", "");
                } else {
                    throw new BytzBootException("请求c4c异常，找不到__next中skipToken");
                }
            }
        }
    }
}
